<template>
  <ActionTable :showBack="false" @addRow="showModal('ADD', { isOpen: 0 })" />
  <a-table
    :columns="columns"
    :row-key="(record) => record.id"
    :data-source="managerOfUser"
    :pagination="state.pagination"
    :loading="state.loading"
    @change="handleTableChange"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'isOpen'">
        <a-switch
          :checked="record.isOpen === 1"
          checked-children="开启"
          un-checked-children="关闭"
          @click="(checked) => showUserState(checked, record)"
        />
      </template>
      <template v-if="column.key === 'action'">
        <TableRowAction :showSelect="false" @updateItem="showModal('UPDATE', record)">
          <a-button class="btn-role" type="primary" @click="setUserRole(record.id)"
            >角色</a-button
          >
        </TableRowAction>
      </template>
    </template>
  </a-table>
  <contextHolder />
</template>
<script lang="ts" setup>
import { addManager, updateManager, selectAllByPage } from "@/api/system/user";
import { ref, onMounted, reactive, h } from "vue";
import { TableProps, Modal, message as $message } from "ant-design-vue";
import UserSchemas from "./userSchemas.vue";
import UserRoleSchemas from "./userRoleSchemas.vue";
import { modalTitleEnum } from "@/enums/modalEnum";
import { getRoleByManagerId, updateManageRole } from "@/api/system/user-role";
import { paginationToQuery } from "@/utils/common";
const [modal, contextHolder] = Modal.useModal();
const childRef = ref();
const columns = [
  {
    dataIndex: "id",
    title: "ID",
    key: "id",
    align: "center",
  },
  {
    dataIndex: "username",
    title: "用户名",
    key: "username",
    align: "center",
  },
  {
    dataIndex: "isOpen",
    title: "状态",
    key: "isOpen",
    align: "center",
  },
  {
    title: "操作",
    key: "action",
    align: "center",
  },
];
const state = reactive({
  loading: true,
  pagination: {
    pageSize: 10,
    current: 1,
    total: 0,
    showTotal: (total) => `总${total}条`,
  },
});
const managerOfUser = ref<API.UserManagerItem[]>();

/**
 * 获取数据
 */
const loadData = async () => {
  const { seachList, seachTotal } = await selectAllByPage(
    paginationToQuery(state.pagination)
  );
  managerOfUser.value = seachList;
  state.pagination.total = seachTotal;
  state.loading = false;
};

/**
 * 更新管理员状态
 * @param checked
 * @param data
 */
const showUserState = async (checked, data) => {
  const { msg } = await updateManager({ id: data.id, isOpen: checked ? 1 : 0 });
  msg === "success" ? loadData() : $message.error(msg);
};

/**
 * 切换分页
 * @param page
 */
const handleTableChange: TableProps["onChange"] = (page) => {
  state.pagination.current = page.current!;
  loadData();
};

/**
 * 设置用户角色
 * @param managerId
 */
const setUserRole = async (managerId) => {
  const { data } = await getRoleByManagerId({ managerId });
  const roleId = data ? data.id : 0;
  const contentSlot = () => h(UserRoleSchemas, { ref: childRef, roleId });
  modal.confirm({
    title: "设置用户角色",
    icon: null,
    okText: "提交",
    cancelText: "取消",
    closable: true,
    content: contentSlot,
    async onOk() {
      const roleId = childRef.value.roleId;
      const { msg } = await updateManageRole({ roleId, userId: managerId });
      msg === "success" ? loadData() : $message.error(msg);
    },
    onCancel() {
      Modal.destroyAll();
    },
  });
};

/**
 * 创建弹窗
 * @param type
 * @param data
 */
const showModal = (type: string, data?: any) => {
  const contentSlot = () => h(UserSchemas, { ref: childRef, formData: data });
  modal.confirm({
    title: modalTitleEnum[type] + "管理员用户",
    icon: null,
    okText: "提交",
    cancelText: "取消",
    closable: true,
    content: contentSlot,
    async onOk() {
      const { id, username, isOpen, password } = childRef.value.formState;
      if (type === "ADD") {
        const { msg } = await addManager({ username, isOpen, password });
        msg === "success" ? loadData() : $message.error(msg);
      } else if (type === "UPDATE") {
        const { msg } = await updateManager({ id, username, isOpen, password });
        msg === "success" ? loadData() : $message.error(msg);
      }
    },
    onCancel() {
      Modal.destroyAll();
    },
  });
};
onMounted(() => {
  loadData();
});
</script>
<style lang="less" scoped>
.btn-role {
  margin-left: 10px;
}
</style>
